/* eslint-disable strict */
/* eslint-disable no-unused-vars */
const ws = require('nodejs-websocket');

const server = ws.createServer(socket => {

  console.log('socket.io连接成功', socket.headers.name);
  // 进入直播间返回系统消息 ，第一次链接返回的消息
  talk(JSON.stringify({
    name: '系统消息',
    comment: '欢迎' + socket.headers.name + '来到直播间',
  }));
  // 返回给前端 接到前端发来的消息
  socket.on('text', data => {
    console.log('received: ' + data);
    const userData = JSON.parse(data);

    talk(JSON.stringify({
      name: userData.name,
      comment: userData.comment,
      img: userData.img,
    }));
    // socket.sendText();
  });
  socket.on('close', (code, reason) => {
    console.log('connection closed!');
  });
  socket.on('error', () => {
    console.log('connection error!');
  });
});


// 把信息发送给所有服务器
function talk(msg) {
  server.connections.forEach(connect => {
    connect.send(msg);
  });
}

server.listen('8000', () => {
  console.log('websocket server start at ws://10.31.71.55:8000');
});
